package com.chatplus.application.common.util;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.Color;
import java.awt.Image;
import java.io.InputStream;
import java.util.Base64;

public class CreateCodeUtil {

    static final SouthernQuietLogger LOGGER = SouthernQuietLoggerFactory.getLogger(CreateCodeUtil.class);

    private CreateCodeUtil() {
    }

    /**
     * 生成二维码--返回BufferedImage
     */
    public static String genQrcode(String text, int size, String imgLogoPath) {
        try {
            InputStream is = ResourcesUtils.getResourceInputStream(imgLogoPath);
            Image image = ImageIO.read(is);
            int scaledSize = size / 9;
            Image scaledLogo = ImgUtil.scale(image, scaledSize, scaledSize);
            ResourcesUtils.getResourceContentString(imgLogoPath);
            QrConfig config = new QrConfig(size, size);
//            config.setMargin(3);
            config.setForeColor(Color.BLACK.getRGB());
            config.setBackColor(Color.WHITE.getRGB());
            config.setImg(scaledLogo);//附带logo
            config.setErrorCorrection(ErrorCorrectionLevel.L);
            byte[] imageBytes = QrCodeUtil.generatePng(text, config);
            String base64Image = Base64.getEncoder().encodeToString(imageBytes);
            return "data:image/jpg;base64, " + base64Image;
        } catch (Exception e) {
            LOGGER.message("生成二维码失败").exception(e).error();
        }
        return null;
    }
}

